package com.oly.cms.hand.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import com.oly.cms.hand.security.CustomAuthenticationDetailsSource;

import static org.springframework.security.config.Customizer.withDefaults;
import com.oly.cms.hand.security.CustomAuthenticationProvider;
import com.oly.cms.hand.security.hand.MyAuthenticationFailureHandler;
import com.oly.cms.hand.security.hand.MyAuthenticationSuccessHandler;
import com.oly.cms.hand.security.hand.MyLogoutSuccessHandler;
import com.oly.cms.hand.security.hand.RedisTokenRepositoryImpl;
import com.oly.cms.hand.security.hand.UnauthorizedEntryPoint;
import com.oly.cms.hand.security.service.WebUserDetailsService;

/**
 * spring security配置
 * 
 * @author grace
 */
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 自定义用户认证逻辑
     */
    @Autowired
    private WebUserDetailsService userDetailsService;

    @Autowired
    private CustomAuthenticationDetailsSource authenticationDetailsSource;

    @Autowired
    private CustomAuthenticationProvider authenticationProvider;

    @Autowired
    private MyAuthenticationFailureHandler failureHandler;

    @Autowired
    private MyAuthenticationSuccessHandler successHandler;

    @Autowired
    private MyLogoutSuccessHandler logoutOutHandler;

    @Autowired
    private RedisTokenRepositoryImpl repository;

    /**
     * 解决 无法直接注入 AuthenticationManager
     *
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 配置HTTP安全设置，定义Spring Security的访问规则和行为。
     * 
     * @param http 用于配置HttpSecurity的接口，可定制应用程序的请求处理方式，例如认证、授权、CSRF保护等。
     * @throws Exception 如果配置过程中发生错误，则抛出异常。
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 添加认证异常入口
        http.exceptionHandling(handling -> handling.authenticationEntryPoint(new UnauthorizedEntryPoint()))
                .authorizeRequests(requests -> requests
                        // 允许匿名访问
                        .antMatchers(HttpMethod.GET, "/**", "/static/**", "/*/login", "/*/register", "/*/api/**")
                        .permitAll()
                        // 允许匿名访问
                        .antMatchers(HttpMethod.POST, "/web/theme/**", "/web/hand/user/register", "/*/general/**",
                                "/*/user/**")
                        .permitAll()
                        // 需要认证
                        .antMatchers(HttpMethod.POST, "/*/hand/**", "/*/register").authenticated()
                        .anyRequest().authenticated())
                .formLogin(login -> login
                        // loginPage 登录页面 loginProcessingUrl 登录处理
                        .loginPage("/*/login").permitAll().loginProcessingUrl("/*/login")
                        .failureHandler(failureHandler)
                        .successHandler(successHandler)
                        .authenticationDetailsSource(authenticationDetailsSource));
        // 启用记住密码
        http.authorizeRequests(withDefaults())
                .rememberMe(me -> me.tokenValiditySeconds(5 * 24 * 60 * 60).tokenRepository(repository)
                        .userDetailsService(userDetailsService));
        http.logout(logout -> logout.logoutUrl("/*/logout").logoutSuccessHandler(logoutOutHandler));

        http.csrf(csrf -> csrf.disable());
    }

    /**
     * 强散列哈希加密实现
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 身份认证接口
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
        auth.authenticationProvider(authenticationProvider);
    }

}
